<template>
  <div>
    <el-row :gutter="10">
      <!-- 机构树-->
      <el-col :span="5">
        <el-tabs v-model="activeName" style="background-color: white" type="card">
          <el-tab-pane label="组织机构" name="zzjg">
            <el-row style="position: relative">
              <el-col :span="20" style="overflow: auto;width: 100%;" :style="{height:heightTree}">
                <el-tree
                  ref="tree"
                  :props="props"
                  :load="loadNode"
                  lazy
                  @node-click="itemClick"
                  :expand-on-click-node="false"
                  :highlight-current="true"
                  style="min-width: 100%;display: inline-block;background-color: transparent"
                >
          <span slot-scope="{ node, data }">
            <span>
              <i v-bind:class="data.icon"></i>{{ node.label }}<el-badge v-show="data.isRead > 0 && data.id != 0" value="new" class="item"></el-badge>
            </span>
          </span>
                </el-tree>

              </el-col>
            </el-row>
<!--            <el-checkbox v-model="isContain" style="margin: 10px 0px 10px 20px">包含下级</el-checkbox>-->
          </el-tab-pane>
        </el-tabs>
      </el-col>

      <!--列表-->
      <el-col :span="19">
        <el-row v-if="role === '系统管理员'||role.indexOf('干部')>-1" style=" background: #fff;height: 50px" class="pt-2 pb-2 pl-3 pr-3">
            <div style="float: right;">
              选择年度:
              <el-select style="width: 100px;margin-right: 10px" v-model="assessYear" placeholder="选择年度" @change = "selectDateChange">
                <el-option
                  v-for="item in assessYearOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
              <!--<el-button style="margin-right: 10px;margin-top: 10px" type="primary" plain
                         @click="downExcel()">&nbsp;激励指标导出
              </el-button>-->
              <!--<el-button style="margin-right: 10px;margin-top: 10px" type="primary" plain
                         @click="refresh()">&nbsp;刷新
              </el-button>-->
              <el-button style="margin-right: 10px;margin-top: 10px" type="primary" plain
                         @click="oneRead('1')">&nbsp;一键已读
              </el-button>
            </div>
        </el-row>
        <!-- table -->
        <el-table
          ref="mytable"
          :height="heightY"
          :data="tableData"
          style="width: 100%;margin-top: 10px"
          border
          highlight-current-row
          @current-change="selectChange"
        >
          <el-table-column
            prop="auditLog"
            label="日志"
            show-overflow-tooltip
            align="center">
            <template slot-scope="scope">
              <span v-html="scope.row.auditLog"></span>
            </template>
          </el-table-column>
          <el-table-column
            prop="operationUser"
            label="操作人"
            show-overflow-tooltip
            width="180px"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="UPDATE_TIME"
            label="操作时间"
            width="180px"
            align="center"
          >
            <template slot-scope="scope">
              {{formatDate(scope.row.UPDATE_TIME)}}
            </template>
          </el-table-column>
          
          <el-table-column
            v-if="assessYear === '2024'"
            prop="COMMIT_TIME"
            label="上报时间"
            width="180px"
            align="center"
          >
            <template slot-scope="scope">
              {{formatDate(scope.row.COMMIT_TIME)}}
            </template>
          </el-table-column>
          <el-table-column
            v-if="assessYear === '2024'"
            prop="shTime"
            label="审核时间"
            width="180px"
            align="center"
          >
            <template slot-scope="scope">
              {{formatDate(scope.row.shTime)}}
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <div class="row" style="background: #fff;">
          <div class="col-sm text-sm-left text-left3 pt-3">
            <vxe-pager
              background
              align="left"
              :current-page.sync="currentPage"
              :page-size.sync="pageSize"
              :total="totalItems"
              :layouts="['PrevJump', 'PrevPage', 'JumpNumber', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
              @page-change="handleSizeChange">
            </vxe-pager>
          </div>
        </div>
      </el-col>
    </el-row>
    <audit-Details ref="dialogAuditDetails" @auditInitData="initData()"/>
  </div>
</template>

<script>
  /*组件引用*/
  import auditDetails from '@/views/young/evaluation/infoAudit/auditDetails.vue'
  /*方法引用*/
  import {getAuditList,getJGList,updateRead,updateTaskRead,getB01ByParentId,selectRole,downExcel} from '@/api/young/evaluation/evaluationConfig/evaluation.js'
  import store from '@/store'

  export default {
    name: "index",
    components: {
      'audit-Details': auditDetails,
    },

    data: () => ({
      props: {
        label: 'name',
        children: 'zones',
        isLeaf: 'leaf',
        icon: '',
        total:''
      },
      heightTree: window.innerHeight - 170 + 'px',
      heightY: window.innerHeight - 230 + 'px',

      activeName: 'zzjg',
      auditLog: '',//暂时不用
      isRead:0,
      tableData:[],
      taskList:[],
      role:'',
      node:{},
      assessYear:'2024',
      assessYearOption: [{
        value: '2022',
        label: '2022'
      }, {
        value: '2023',
        label: '2023'
      },{
        value: '2024',
        label: '2024'
      }],

      //分页
      totalItems: 0,
      currentPage: 1,
      pageSize: 20,
    }),

    mounted() {
      this.$nextTick(() => {
        setTimeout(()=>{
          this.heightY = window.innerHeight - 230 + 'px';
        },100)
      });
      this.initData();
    },

    methods: {

      initData(year) {
        const params = {
          'page': this.currentPage, // 当前多少页
          'rows': this.pageSize, // 每页显示数据
          'userId': store.getters.user_id.toString(),
          'assessYear':this.assessYear,
        };
        this.logChoose(params)
        const param = {
          "userInfo" : JSON.parse(sessionStorage.getItem(`userInfo`)),
        };
        selectRole(param).then(result=>{
          this.role = '';
          var roles = '';
          result.resultdata.forEach((item)=>{
            roles += item;
          })
          if (roles.indexOf("系统管理员")>-1){
            this.role = "系统管理员";
          }else if (roles.indexOf("干部一处")>-1){
            this.role = "干部一处";
          }else if (roles.indexOf("干部二处")>-1){
            this.role = "干部二处";
          }else if (roles.indexOf("干部三处")>-1){
            this.role = "干部三处";
          }else if (roles.indexOf("干部四处角色")>-1){
            this.role = "干部四处";
          }else if (roles.indexOf("干部五处")>-1){
            this.role = "干部五处";
          }
          console.log(this.role.indexOf('干部'),"112")
        });
      },

      //分页查询
      handleSizeChange({currentPage, pageSize}) {
        this.currentPage = currentPage
        this.perPage = pageSize
        this.initData()
      },

      //加载机构树
      loadNode(node, resolve) {
        let params
        if (node.level === 0) {
          this.node = node;
          // 获得parentId = -1 的树
          params = {
            'userId': store.getters.user_id.toString(),
            'parentId': '-1',
            'assessYear':this.assessYear
          }
        } else {
          params = {
            'userId': store.getters.user_id.toString(),
            'parentId': node.data.id,
            'assessYear':this.assessYear
          }
        }
        getB01ByParentId(params).then((data) => {
          data.resultdata.forEach((item) => {
            if (item.b0194 == '3') {
              item.icon = 'customRoot-icon'
            } else if (item.b0194 == '2') {
              item.icon = 'customChildren-icon'
            } else if (item.b0194 == '1') {
              item.icon = 'customParent-icon'
            }
          })
          return resolve(data.resultdata)
        })
      },

      //点击机构树的节点事件
      itemClick(node,data) {
        /*查询机构有没有任务*/
        const taskParam = {
          "dw_bianma" : node.jgid,
          "year" : this.assessYear
        };
        getJGList(taskParam).then(data => {
          if (data.result) {
            this.taskList = data.resultdata
            if (data.resultdata.length != 0) {
                this.$nextTick(() => {
                  this.$refs.dialogAuditDetails.initShow(this.role,node,this.assessYear)
                })
            }
          } else {
            this.$message.error(data.message)
          }
          this.loading = false;
        });

        /*更改机构树未读状态*/
        var nodeParams = {
          'userId': store.getters.user_id.toString(),
          'parentId': node.id
        }
        getB01ByParentId(nodeParams).then((result) => {
          this.isRead = 0;
          result.resultdata.forEach((item) => {//需要判断,子节点有没有未读(1)的
            if (item.isRead != 0) {//子节点有未读(1)的,记录一下,用于下一步判断
              this.isRead+=item.isRead
            }
          })
          if (this.isRead == 0 && node.isRead != 0){//如果子节点没有未读(1)的,就改变状态
            const params = {
              'jgId': node.jgid,
              'role':this.role,
              "assessYear" : this.assessYear
            };
            updateTaskRead(params);
            this.updateIsRead(data)
          }
        })
      },

      //更改机构树的已读状态
      updateIsRead(data){
        if (data.data !== undefined && data.data.id !== '0') {
          data.data.isRead = 0
          this.updateIsRead(data.parent)
        }
      },

      //查询日志列表
      async logChoose(prams) {
        await getAuditList(prams).then(data => {
          if (data.result) {
            console.log(data.resultdata)
            if (data.resultdata) {
              if (data.result) {
                this.tableData = []
                this.totalItems = data.resultdata.total // 设置总记录数
                this.tableData = data.resultdata.rows // 填充列表数据
                this.$nextTick(() => {
                  this.$refs.mytable.doLayout()
                })
              } else {
                this.$message.error(item.message)
              }
            }
          } else {
            this.$message.error(data.message)
          }
          this.loading = false;
        })
      },

      //一键已读(更改日志列表状态)
      async oneRead(type){
        const params = {
          "assessYear" : this.assessYear
        };
        await updateRead(params);
        this.initData()
      },

      //刷新(刷新机构树与日志列表)
      async refresh(){
        this.initData();
        let node = this.$refs.tree.getNode(this.node);
        //设置未进行懒加载状态
        node.loaded = false;
        //重新展开节点就会间接重新触发load达到刷新效果
        node.expand();
        this.$forceUpdate();
      },

      formatDate(time){
        if(time === null || time === "null" || time === undefined || time === "undefined"){
          strDate = "";
          return strDate;
        }else{
          var date = new Date(time);
          var Y = date.getFullYear() + "-";
          var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
          var D = (date.getDate() < 10 ? '' + (date.getDate()) : date.getDate()) + " "
          var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
          var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
          var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
          var strDate = Y + M + D + h + m + s;
          return strDate;
        }
      },
      //下拉框数据改变change
      selectDateChange(){
        // this.initFillingData(new Date(this.assessYear).getFullYear())
        this.initData();
        let node = this.$refs.tree.getNode(this.node);
        //设置未进行懒加载状态
        node.loaded = false;
        //重新展开节点就会间接重新触发load达到刷新效果
        node.expand();
        this.$forceUpdate();
      },
      //选中列表的一行数据(暂时不用)
      selectChange(currentRow) {
        this.auditLog = currentRow
      },
        //下载激励指标汇总
        downExcel(){
            const month= new Date().getMonth() + 1;
            const user =JSON.parse(sessionStorage.getItem(`userInfo`));
            const params = {
                page: this.currentPage, // 当前多少页
                rows: this.pageSize, // 每页显示数据
                userId: user.userId,
                assessYear: this.assessYear,
                fileName:"激励指标汇总表(" +
                    new Date().getFullYear() +"年"+month+ "月).xls"
            }
            this.$confirm('是否下载?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.loading = true;
                downExcel(params).then(result => {
                    this.loading = false;
                })
            })

        },
    }
  }


</script>

<style scoped>
  .swiper-container {
    --swiper-theme-color: #ff6600; /* 设置Swiper风格 */
    --swiper-navigation-color: #909399; /* 单独设置按钮颜色 */
    --swiper-navigation-size: 15px; /* 设置按钮大小 */
  }

  .customRoot-icon {
    width: 20px;
    height: 16px;
    display: inline-block;
    background: url('../../../../assets/images/students/customRoot.png') no-repeat;

  }

  .customParent-icon {
    width: 20px;
    height: 20px;
    display: inline-block;
    /*background: url("../images/students/customParent.png");*/
    background: url('../../../../assets/images/students/customParent.png') no-repeat;
  }

  .customChildren-icon {
    width: 20px;
    height: 18px;
    display: inline-block;
    /*background: url("../images/students/customChildren.png");*/
    background: url('../../../../assets/images/students/customChildren.png') no-repeat;
  }
</style>
